package com.gobang.controller;

import com.gobang.domain.dto.auth.LoginRequest;
import com.gobang.domain.dto.auth.RegisterRequest;
import com.gobang.domain.vo.Result;
import com.gobang.domain.vo.auth.AuthResponse;
import com.gobang.domain.vo.auth.UserInfoVO;
import com.gobang.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 处理用户注册、登录等认证相关接口
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;

    /**
     * 用户注册
     *
     * @param request 注册请求
     * @return 操作结果
     */
    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody RegisterRequest request) {
        log.info("用户注册请求: username={}", request.getUsername());
        userService.register(request);
        return Result.success("注册成功，请前往登录");
    }

    /**
     * 用户登录
     *
     * @param request 登录请求
     * @return 认证响应（包含Token）
     */
    @PostMapping("/login")
    public Result<AuthResponse> login(@Valid @RequestBody LoginRequest request) {
        log.info("用户登录请求: username={}", request.getUsername());
        AuthResponse response = userService.login(request);
        return Result.success(response);
    }

    /**
     * 检查用户名是否可用
     *
     * @param username 用户名
     * @return true-可用，false-已存在
     */
    @GetMapping("/check-username")
    public Result<Boolean> checkUsername(@RequestParam String username) {
        boolean exists = userService.isUsernameExists(username);
        return Result.success(!exists);
    }

    /**
     * 用户登出
     *
     * @param request HTTP请求（从请求头中获取Token）
     * @return 操作结果
     */
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String token = null;
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        }

        log.info("用户登出请求");
        userService.logout(token);
        return Result.success("登出成功");
    }
}

